#include "Sock.hpp"
#include "Protocol.hpp"

void Usage(const string s)
{
    cout << "Usage : " << s << " server_port" << endl;
}

void *handler(void *psock)
{
    pthread_detach(pthread_self());
    int sock = *(int *)psock;
    delete (int *)psock;

#define NUM 1024
    char buf[NUM];
    memset(buf, 0, sizeof(buf));

    ssize_t sz = read(sock, buf, sizeof(buf) - 1);
    if (sz > 0)
    {
        buf[sz] = 0;
        request_t rq;
        string json_str(buf);
        cout << json_str << endl;
        DeserializeRequest(json_str, rq);

        response_t rp;

        switch (rq._op)
        {
        case '+':
            rp.result = rq._dataFirst + rq._dataSecond;
            break;
        case '-':
            rp.result = rq._dataFirst - rq._dataSecond;
            break;
        case '*':
            rp.result = rq._dataFirst * rq._dataSecond;
            break;
        case '/':
            if (rq._dataSecond == 0)
            {
                rp.code = 1;
                break;
            }
            rp.result = rq._dataFirst / rq._dataSecond;
            break;
        case '%':
            if (rq._dataSecond == 0)
            {
                rp.code = 2;
                break;
            }
            rp.result = rq._dataFirst % rq._dataSecond;
            break;
        default:
            rp.code = 3;
            break;
        }

        string ret(SerializeResponse(rp));
        write(sock, ret.c_str(), ret.size());
    }
    else if (sz == 0)
    {
        cout << "客户端退出" << endl;
    }
    else
    {
        cerr << "read failed" << endl;
    }
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(-1);
    }
    int sock = Sock::Socket();

    uint16_t port = atoi(argv[1]);

    Sock::Bind(sock, port);

    Sock::Listen(sock);

    while (true)
    {
        int new_sock = Sock::Accept(sock);
        int *psock = new int(new_sock);
        pthread_t tid;
        pthread_create(&tid, nullptr, handler, (void *)psock);
    }

    // 反序列化：字符串->结构体
    // string json_str(R"({"operator":43,"x":1,"y":2})");
    // // cout << json_str << endl;
    // Json::Value root;
    // Json::Reader reader;
    // reader.parse(json_str, root);// 将json串中kv结构转换到root中
    // int data1 = root["x"].asInt();
    // int data2 = root["y"].asInt();
    // char op = root["operator"].asUInt();
    // request_t rq{data1, data2, op};
    // cout << rq._dataFirst << rq._op << rq._dataSecond << endl;

    // 序列化：结构体->字符串
    // request_t rq{1,2,'+'};
    // Json::Value root; // kv结构
    // root["x"] = rq._dataFirst;
    // root["y"] = rq._dataSecond;
    // root["operator"] = rq._op;

    // Json::Writer是一个基类，不能直接使用，一般使用它的子类
    // StyledWriter —— 格式化的Json字符串
    // FasterWriter —— 快速转换的Json字符串
    // Json::StyledWriter writer;
    // Json::FastWriter writer;
    // string json_str = writer.write(root);
    // cout << json_str << endl;
    return 0;
}